<template>
  <div class="nurse-assign-container">
    <!-- 页面标题区域 -->
    <div class="page-header">
      <h1>护理员分配管理</h1>
      <div class="header-actions">
        <el-button 
          type="primary" 
          icon="Refresh" 
          size="small" 
          @click="handleRefresh"
        >
          刷新数据
        </el-button>
      </div>
    </div>

    <!-- 楼层切换标签 -->
    <div class="floor-tabs">
      <el-button 
        v-for="floor in floorList" 
        :key="floor.id"
        class="floor-tab"
        :class="{ active: currentFloor === floor.id }"
        @click="handleFloorChange(floor.id)"
      >
        {{ floor.floorName }}
      </el-button>
    </div>

    <!-- 房间列表区域 -->
    <div class="rooms-list">
      <el-card 
        v-for="room in filteredRooms" 
        :key="room.id"
        shadow="hover"
        class="room-card"
      >
        <!-- 房间头部（房间号 + 批量设置按钮） -->
        <div class="room-header">
          <span class="room-number">房间号: {{ room.roomNo }}</span>
          <el-button 
            type="primary" 
            size="small" 
            class="batch-btn"
            @click="handleBatchSet(room)"
          >
            批量设置护理员
          </el-button>
        </div>

        <!-- 床位网格布局 -->
        <div class="beds-grid">
          <div 
            class="bed-item" 
            v-for="bed in room.bedList" 
            :key="bed.id"
          >
            <!-- 床位基础信息 -->
            <div class="bed-info">
              <div>床位号: {{ bed.bedNo }}</div>
              <div>老人姓名: {{ bed.elderly?.name || '空闲' }}</div>
            </div>

            <!-- 单个床位设置按钮 -->
            <el-button 
              type="text" 
              class="set-nurse-btn"
              @click="handleSetNurse(bed)"
            >
              设置护理员
            </el-button>

            <!-- 已分配护理员标签展示 -->
             <div class="wai-nurses">
              <div>已分配护理员:</div>
            <div class="nurses">
              <template v-if="bed.nurses && bed.nurses.length > 0">
                <el-tag 
                  v-for="(nurse, index) in bed.nurses" 
                  :key="nurse.userId"
                  closable
                  @close="handleRemoveNurse(bed, index)"
                  :max-length="4"
                  :ellipsis="true"
                >
                  {{ nurse.nickName }}
                </el-tag>
              </template>
              <template v-else>
                <span class="no-nurse">当前床位没有安排护理员</span>
              </template>
            </div></div>
          </div>

          <!-- 空床位提示 -->
          <div v-if="!(room.bedList && room.bedList.length)" class="empty-bed">
            当前房间没有安排床位
          </div>
        </div>
      </el-card>
    </div>

    <!-- 单个床位设置护理员弹窗 -->
    <el-dialog 
      v-model="dialogVisible" 
      title="设置护理员" 
      width="400px"
    >
      <div class="nurse-checkbox-group">
        <el-checkbox 
          v-for="nurse in nurseList" 
          :key="nurse.userId"
          :label="nurse.userId" 
          v-model="selectedNurseIds"
        >
          {{ nurse.nickName }}
        </el-checkbox>
      </div>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmSetNurse">确定</el-button>
      </template>
    </el-dialog>

    <!-- 房间批量设置护理员弹窗 -->
    <el-dialog 
      v-model="batchDialogVisible" 
      title="批量设置护理员" 
      width="400px"
    >
      <div class="nurse-checkbox-group">
        <el-checkbox 
          v-for="nurse in nurseList" 
          :key="nurse.userId"
          :label="nurse.userId" 
          v-model="batchSelectedNurseIds"
        >
          {{ nurse.nickName }}
        </el-checkbox>
      </div>
      <template #footer>
        <el-button @click="batchDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmBatchSet">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
// 导入Vue核心API
import { ref, computed, onMounted } from 'vue';
// 导入Element Plus组件和图标
import { ElMessage, ElDialog, ElCheckbox, ElTag, ElButton, ElCard } from 'element-plus';
import { Refresh } from '@element-plus/icons-vue';

// 导入接口（请替换为实际项目中的接口路径）
import { listFloorAllRelations } from '@/api/system/roomManage';
import { listUser } from '@/api/system/user';
// 新增：导入护理员床位绑定相关接口
import { 
  setBedCaregivers, 
  batchSetBedCaregivers, 
  removeBedCaregiver,
  getByBedId 
} from '@/api/system/hlyandcw';

// 1. 状态管理定义
const floorList = ref([]);          // 所有楼层数据（含房间、床位关联信息）
const nurseList = ref([]);         // 所有护理员列表
const currentFloor = ref('');       // 当前选中的楼层ID
const dialogVisible = ref(false);   // 单个床位设置弹窗显示状态
const batchDialogVisible = ref(false); // 批量设置弹窗显示状态
const currentBed = ref(null);       // 当前操作的床位数据
const currentRoom = ref(null);      // 当前操作的房间数据
const selectedNurseIds = ref([]);   // 单个床位选中的护理员ID数组
const batchSelectedNurseIds = ref([]); // 批量设置选中的护理员ID数组

// 2. 计算属性：筛选当前楼层的房间列表
const filteredRooms = computed(() => {
  if (floorList.value.length === 0) return [];
  const currentFloorData = floorList.value.find(floor => floor.id === currentFloor.value);
  return currentFloorData?.roomList || [];
});

// 3. 页面初始化钩子
onMounted(async () => {
  try {
    // 并行加载楼层和护理员数据
    await Promise.all([
      loadFloorList(),
      loadNurseList()
    ]);
  } catch (error) {
    ElMessage.error(`页面初始化失败：${error.message || '网络异常'}`);
  }
});

// 4. 数据加载方法
/**
 * 加载所有楼层关联数据（楼层-房间-床位）
 */
const loadFloorList = async () => {
  try {
    const res = await listFloorAllRelations();
    if (res.code === 200 && Array.isArray(res.data)) {
      floorList.value = res.data;
      // 初始化默认选中第一个楼层
      if (floorList.value.length > 0) {
        currentFloor.value = floorList.value[0].id;
      }
      
      // 为每个床位加载护理员数据
      await loadAllBedNurses();
    } else {
      ElMessage.warning('未查询到楼层数据');
    }
  } catch (error) {
    console.error('加载楼层失败:', error);
    ElMessage.error(`加载楼层失败：${error.message || '接口调用异常'}`);
  }
};

/**
 * 加载所有护理员列表（按角色筛选）
 */
const loadNurseList = async () => {
  try {
    // 接口参数：按"护理员"角色筛选（请根据实际接口调整参数）
    const res = await listUser({ role: '护理员' });
    if (res.code === 200 && Array.isArray(res.rows)) {
      nurseList.value = res.rows;
    } else {
      ElMessage.warning('未查询到护理员数据');
    }
  } catch (error) {
    console.error('加载护理员失败:', error);
    ElMessage.error(`加载护理员失败：${error.message || '接口调用异常'}`);
  }
};

/**
 * 加载所有床位的护理员数据
 */
const loadAllBedNurses = async () => {
  try {
    // 收集所有床位ID
    const allBedIds = [];
    floorList.value.forEach(floor => {
      floor.roomList?.forEach(room => {
        room.bedList?.forEach(bed => {
          allBedIds.push(bed.id);
        });
      });
    });
    
    if (allBedIds.length === 0) return;
    
    // 批量查询护理员绑定信息
    // 注意：这里需要根据实际接口调整，可能需要分批次查询
    for (const floor of floorList.value) {
      for (const room of floor.roomList || []) {
        for (const bed of room.bedList || []) {
          await loadBedNurses(bed);
        }
      }
    }
  } catch (error) {
    console.error('加载床位护理员失败:', error);
  }
};

/**
 * 加载单个床位的护理员数据
 */
const loadBedNurses = async (bed) => {
  try {
    const res = await getByBedId(bed.id);
    if (res.code === 200 && Array.isArray(res.data)) {
      // 将绑定信息转换为护理员对象
      const nurseIds = res.data.map(binding => binding.caregiverId);
      bed.nurses = nurseList.value.filter(nurse => nurseIds.includes(nurse.userId));
    } else {
      bed.nurses = [];
    }
  } catch (error) {
    console.error(`加载床位 ${bed.id} 的护理员失败:`, error);
    bed.nurses = [];
  }
};

// 5. 交互逻辑方法
/**
 * 切换楼层
 * @param {string} floorId - 目标楼层ID
 */
const handleFloorChange = (floorId) => {
  if (currentFloor.value === floorId) return;
  currentFloor.value = floorId;
};

/**
 * 刷新页面数据
 */
const handleRefresh = async () => {
  try {
    await Promise.all([
      loadFloorList(),
      loadNurseList()
    ]);
    ElMessage.success('数据已成功刷新');
  } catch (error) {
    ElMessage.error(`刷新失败：${error.message || '网络异常'}`);
  }
};

/**
 * 打开单个床位设置弹窗
 * @param {object} bed - 目标床位数据
 */
const handleSetNurse = (bed) => {
  currentBed.value = bed;
  // 初始化选中状态（回显已分配的护理员）
  selectedNurseIds.value = bed.nurses?.map(nurse => nurse.userId) || [];
  dialogVisible.value = true;
};

/**
 * 打开房间批量设置弹窗
 * @param {object} room - 目标房间数据
 */
const handleBatchSet = (room) => {
  currentRoom.value = room;
  // 批量设置初始化为空选
  batchSelectedNurseIds.value = [];
  batchDialogVisible.value = true;
};

/**
 * 移除单个床位的护理员
 * @param {object} bed - 目标床位数据
 * @param {number} index - 要移除的护理员索引
 */
const handleRemoveNurse = async (bed, index) => {
  try {
    const nurse = bed.nurses[index];
    const res = await removeBedCaregiver(bed.id, nurse.userId);
    if (res.code === 200) {
      bed.nurses.splice(index, 1);
      ElMessage.success('已成功移除护理员');
    } else {
      ElMessage.error('移除护理员失败');
    }
  } catch (error) {
    console.error('移除护理员失败:', error);
    ElMessage.error('移除护理员失败');
  }
};

/**
 * 确认单个床位设置护理员
 */
const confirmSetNurse = async () => {
  if (!currentBed.value) return;
  
  try {
    const res = await setBedCaregivers(currentBed.value.id, selectedNurseIds.value);
    if (res.code === 200) {
      // 更新前端显示
      currentBed.value.nurses = nurseList.value
        .filter(nurse => selectedNurseIds.value.includes(nurse.userId))
        .map(nurse => ({ ...nurse }));
      
      dialogVisible.value = false;
      ElMessage.success('护理员设置成功');
    } else {
      ElMessage.error('护理员设置失败');
    }
  } catch (error) {
    console.error('设置护理员失败:', error);
    ElMessage.error('护理员设置失败');
  }
};

/**
 * 确认房间批量设置护理员
 */
const confirmBatchSet = async () => {
  if (!currentRoom.value) return;
  
  try {
    const bedIds = currentRoom.value.bedList.map(bed => bed.id);
    const res = await batchSetBedCaregivers(bedIds, batchSelectedNurseIds.value);
    if (res.code === 200) {
      // 更新前端显示
      const selectedNurses = nurseList.value
        .filter(nurse => batchSelectedNurseIds.value.includes(nurse.userId))
        .map(nurse => ({ ...nurse }));
      
      currentRoom.value.bedList.forEach(bed => {
        bed.nurses = [...selectedNurses];
      });
      
      batchDialogVisible.value = false;
      ElMessage.success('批量设置护理员成功');
    } else {
      ElMessage.error('批量设置护理员失败');
    }
  } catch (error) {
    console.error('批量设置护理员失败:', error);
    ElMessage.error('批量设置护理员失败');
  }
};
</script>

<!-- 样式保持不变 -->
<style scoped>
/* 原有的样式代码保持不变 */
/* 页面容器基础样式 */
.nurse-assign-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

/* 页面标题样式 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
.page-header h1 {
  margin: 0;
  font-size: 24px;
  color: #333;
}
.header-actions {
  display: flex;
  gap: 10px;
}

/* 楼层标签样式 */
.floor-tabs {
  display: flex;
  margin-bottom: 20px;
  gap: 4px;
}
.floor-tab {
  padding: 8px 16px;
  background-color: #e5e7eb;
  border: none;
  cursor: pointer;
  border-radius: 4px 4px 0 0;
  font-size: 14px;
  transition: all 0.2s;
}
.floor-tab.active {
  background-color: #fff;
  font-weight: bold;
  box-shadow: 0 -2px 0 0 #42b983 inset;
}

/* 房间列表样式 */
.rooms-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}
.room-card {
  transition: all 0.3s ease;
}
.room-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.08) !important;
}

/* 房间头部样式 */
.room-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 1px dashed #eee;
}
.room-number {
  font-weight: bold;
  font-size: 16px;
  color: #333;
}
.batch-btn {
  font-size: 14px;
  padding: 6px 12px;
}

/* 床位网格样式 */
.beds-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
}
.bed-item {
  background-color: #f9f9f9;
  border-radius: 4px;
  padding: 12px;
  display: flex;
  flex-direction: column;
  transition: all 0.2s;
}
.bed-item:hover {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

/* 床位信息样式 */
.bed-info {
  margin-bottom: 12px;
  font-size: 14px;
  color: #333;
  
  
}
.bed-info div {
  margin-bottom: 4px;
  padding: 4px 0;
  font-size: 15                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             px;
  /* margin: 10px 0; */
}

.wai-nurses {
  display: flex;
  flex-direction: column;
  gap: 4px;
}



.set-nurse-btn {
  align-self: flex-end;
  margin-bottom: 12px;
  padding: 0;
  font-size: 14px;
}

/* 护理员标签样式 */
.nurses {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
  margin-top: auto;
}
.nurses ::v-deep .el-tag {
  font-size: 12px;
  padding: 3px 8px;
}
.no-nurse {
  color: #999;
  font-size: 12px;
}

/* 空床位提示样式 */
.empty-bed {
  grid-column: 1 / -1;
  text-align: center;
  padding: 30px 0;
  color: #999;
  font-size: 12px;
  border: 1px dashed #ebeef5;
  border-radius: 6px;
  background-color: #fafafa;
}

/* 护理员多选框组样式 */
.nurse-checkbox-group {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  max-height: 300px;
  overflow-y: auto;
}
.nurse-checkbox-group .el-checkbox {
  width: calc(50% - 6px); /* 两行布局，优化显示效果 */
}

/* 响应式适配 */
@media (max-width: 1200px) {
  .beds-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}
@media (max-width: 768px) {
  .beds-grid {
    grid-template-columns: 1fr;
  }
  .room-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  .header-actions {
    width: 100%;
    justify-content: flex-end;
  }
}
</style>